<script setup>
import {ref} from "vue";
import SubmitAnswer from "../../student/practice/SubmitAnswer.vue";
import DoAnswer from "./DoAnswer.vue";
import router from "../../../router/index.js";
import {
  faceCompare,
  getAssignment,
  getExam, getExamQuestionOptions,
  listAssignmentQuestions,
  listExamQuestions, submitAnswer, submitExam
} from "../../../api/course/course.js";
import {ArrowLeftBold, ArrowRightBold} from "@element-plus/icons-vue";
import {ElMessage, ElNotification} from "element-plus";
// 题型数组
const type = ref(['单选题', '多选题', '判断题', '填空题', '问答题'])
// 题目数组
const practices = ref([])
// 总题目数
const total = ref(10)
// 单个题目
const question = ref({})
// 作业题目数组(解析个屁,顺序查询)
const examsQuestions = ref([])
// 摄像头对象
let  mediaStreamTrack = null;
// 摄像头是否开启
let cameraOn = false;

// 作业信息
const exam = ref({});
// 当前题目索引
const questionIndex=ref(0);

// 单选选项
const radioOptions = ref([{
  value: 'A',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'B',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'C',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'D',
  content: '',
  checked: 0
}]);
//多选选项
const checkboxOptions = ref([{
  value: 'A',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'B',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'C',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'D',
  content: '',
  checked: 0
}])
// 判断题选项
const judgeOptions = ref([{
  value: 'T',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'F',
  content: '',
  checked: 0 // 选项未选中状态
}])
// 获取题目选项
const handleGetQuestionOptions = async () => {
  await getExamQuestionOptions(question.value.id).then(res => {
    option.value = res.data;
    // 给选项赋值
    assignOption();
  })
}
// 选项对象
const option = ref({
  practiceId: 0,
  a: '',
  b: '',
  c: '',
  d: ''
})
// 判断是否是选择
const isOption = () => {
  if (question.value.type === 0) {
    // console.log("单选");
    option.value.a = radioOptions.value[0].content;
    option.value.b = radioOptions.value[1].content;
    option.value.c = radioOptions.value[2].content;
    option.value.d = radioOptions.value[3].content;
    return true;
  } else if (question.value.type === 1) {
    // console.log("多选");
    option.value.a = checkboxOptions.value[0].content;
    option.value.b = checkboxOptions.value[1].content;
    option.value.c = checkboxOptions.value[2].content;
    option.value.d = checkboxOptions.value[3].content;
    return true;
  } else if (question.value.type === 2) {
    // console.log("判断");
    option.value.a = judgeOptions.value[0].content;
    option.value.b = judgeOptions.value[1].content;
    return true;
  } else return false;
}

// 选项赋值
const assignOption = () => {
  if (question.value.type === 0) {
    radioOptions.value[0].content = option.value.a;
    radioOptions.value[1].content = option.value.b;
    radioOptions.value[2].content = option.value.c;
    radioOptions.value[3].content = option.value.d;
  } else if (question.value.type === 1) {
    checkboxOptions.value[0].content = option.value.a;
    checkboxOptions.value[1].content = option.value.b;
    checkboxOptions.value[2].content = option.value.c;
    checkboxOptions.value[3].content = option.value.d;
  } else if (question.value.type === 2) {
    judgeOptions.value[0].content = option.value.a;
    judgeOptions.value[1].content = option.value.b;
  }
}


// 获取作业id
const examId = ref();
examId.value = router.currentRoute.value.params.id;
console.log(examId.value);

//调用摄像头
function getCamera () {
  let constraints = {
    video: {
      width: 200,
      height: 200
    },
    audio: false
  }
  //获得video摄像头
  let video = document.getElementById('video')
  let promise = navigator.mediaDevices.getUserMedia(constraints)
  promise.then((mediaStream) => {
    mediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[1]
    video.srcObject = mediaStream
    video.play()
    cameraOn = true
  }).catch((back) => {
    this.$message({
      duration: 1500,
      message: '请开启摄像头权限o(╥﹏╥)o!',
      type: 'error'
    })
  })
}

//拍照
async function takePhoto() {
  if (cameraOn) {//摄像头是否开启 开启了才执行上传信用图片
    //获得Canvas对象
    let video = document.getElementById('video')
    let canvas = document.getElementById('canvas')
    let ctx = canvas.getContext('2d')
    ctx.drawImage(video, 0, 0, 200, 200)
    // toDataURL  ---  可传入'image/png'---默认, 'image/jpeg'
    let img = document.getElementById('canvas').toDataURL()
    console.log(img)
    //构造post的form表单
    let formData = new FormData()
    //convertBase64UrlToBlob函数是将base64编码转换为Blob
    formData.append('file', base64ToFile(img, 'examTakePhoto.png'))
    faceCompare(formData).then(res => {
      if ( res.data !== 1 ) {
        ElNotification.error({
          title: '禁止作弊',
          message: '警告！请勿让他人替考，如再次发现将直接按违规处理',
          duration: 1500
        })
      }
    })
  }
}

//将摄像头截图的base64串转化为file提交后台
function base64ToFile(urlData, fileName) {
  let arr = urlData.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bytes = atob(arr[1]) // 解码base64
  let n = bytes.length
  let ia = new Uint8Array(n)
  while (n--) {
    ia[n] = bytes.charCodeAt(n)
  }
  return new File([ia], fileName, {type: mime})
}

// 获取作业信息
const handleGetExam = async () => {
  console.log(examId.value)
  await getExam(examId.value).then(res => {
    exam.value = res.data;
    console.log(exam.value);
    startTimer();
    //   获取作业题目
    handleListExamQuestions()
  })
}
// 获取当前作业所有题目
const handleListExamQuestions = async () => {
  await listExamQuestions(examId.value).then(res => {
    examsQuestions.value = res.data;
    console.log(examsQuestions.value);
    examsQuestions.value.map(question => question.answer = [])
    //   获取第一个题目
    question.value = examsQuestions.value[0];
    if (isOption())
      handleGetQuestionOptions();
    //   解析题目数组为跳转卡片
    handleExamQuestionsToPractices();
  })
}

// 解析题目数组
const handleExamQuestionsToPractices = () => {
  for (let i = 0; i < examsQuestions.value.length; i++) {
    if (!practices.value.map(practice => practice.type).includes(examsQuestions.value[i].type)) {
      practices.value.push({
        type: examsQuestions.value[i].type,
        content: [examsQuestions.value[i]]
      })
      // console.log(practices.value);
    } else {
      // console.log(practices.value.map(practice=>practice.type).indexOf(item));
      // 获取题目内容
      practices.value[practices.value.map(practice => practice.type).indexOf(examsQuestions.value[i].type)].content.push(examsQuestions.value[i]);
    }
  }// console.log(practices.value)
}

// 跳转题目
const handleGetQuestion = (item) => {
  question.value = item;
  questionIndex.value=examsQuestions.value.indexOf(item);
  console.log(questionIndex.value);
  question.value.answer = [];
  if (isOption())
    handleGetQuestionOptions();
}


// 跳转上一题
const handleLeftQuestion = () => {
  question.value=examsQuestions.value[questionIndex.value-1];
  questionIndex.value--;
  if (isOption())
    handleGetQuestionOptions();
}
// 跳转下一题
const handleRightQuestion = () => {
  question.value=examsQuestions.value[questionIndex.value+1];
  questionIndex.value++;
  if (isOption())
    handleGetQuestionOptions();
}


handleGetExam()

//开启摄像头
window.onload = () => {
  setTimeout(() => {
    getCamera()
  }, 1000)

  //生成3次时间点截图
  let times = []
  for (let i = 0; i < 2; i++) {
    times.push(Math.ceil(Math.random() * exam.value.totalTime))
  }
  times.push(10000)
  //一次考试最多3次随机的诚信截图
  times.forEach(item => {
    window.setTimeout(() => {
      takePhoto()
    }, item)
  })
}
// // 提交答案
// function submitQuestionAnswer() {
//   submitAnswer(question.value.answer,question.value.id).then(res => {
//     if ( res.data === '正确' ) {
//       ElNotification.success({
//         title: '提交成功',
//         message: '回答正确',
//         duration: 2000
//       })
//     }else {
//       ElNotification.error({
//         title: '提交成功',
//         message: '回答错误',
//         duration: 2000
//       })
//     }
//   })
// }

// 开启计时器
function startTimer() {
  let minutes = exam.value.totalTime; // 设置计时时间（分钟）
  let seconds = minutes * 60;
  const timerDisplay = document.getElementById('timer');
  const interval = setInterval(() => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    timerDisplay.textContent = `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
    if (seconds > 0) {
      seconds--;
    } else {
      clearInterval(interval);
      ElNotification({
        title: '考试结束',
        message: '考试时间已到，请提交试卷',
        duration: 2000
      })
      handleSubmitExam();
    }
  }, 1000);
}

//todo 提交考试记录
const  handleSubmitExam=()=>{
  submitExam(exam.value.id).then(res => {
    ElMessage.success("考试已提交");
    router.back();
  })
}


</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header style="background: #3a4357;height: 10vh">
        <div style="display: flex; align-items: center; height: 100%;">
          <div id="timer"  style="color: white;">00:00</div>
          <span style="color: white;margin-left: 50%">{{ exam.name }}</span>
          <el-button type="primary" style="margin-left: auto" @click="handleSubmitExam">提交考试</el-button>
        </div>
      </el-header>
      <el-container>
        <el-main style="height: 90vh;position: relative">
          <div style="display: flex;justify-content: space-between;">
            <el-icon size="30" style="margin-top: 42vh" @click="handleLeftQuestion()" v-if="questionIndex!==0">
              <ArrowLeftBold/>
            </el-icon>
            <el-icon size="30" v-if="questionIndex===0"></el-icon>
            <!--          题型-->
            <div>
              <h3>{{ type[question.type] }}</h3>
              <!--          题目-->
              <div style="height: 60vh;display: flex">
                <el-form
                    :label-position="'top'"
                    label-width="auto"
                    :model="question"
                    style="max-width: 900px"
                >
                  <el-form-item label="题目内容">
                    <div>{{ question.content }}</div>
                  </el-form-item>
                  <!--        题目类型选择-->
                  <DoAnswer :practice="question" :radioOptions="radioOptions" :judge-options="judgeOptions"
                            :checkbox-options="checkboxOptions"></DoAnswer>
                </el-form>
              </div>
            </div>
            <el-icon size="30" style="margin-top: 42vh" v-if="questionIndex!==examsQuestions.length-1" @click="handleRightQuestion()">
              <ArrowRightBold/>
            </el-icon>
            <el-icon size="30" v-if="questionIndex===examsQuestions.length-1"></el-icon>

          </div>
<!--          <div class="button-div">-->
<!--            <el-button>取消</el-button>-->
<!--&lt;!&ndash;            <el-button type="success" @click="submitQuestionAnswer(questionIndex)">提交当前题目答案</el-button>&ndash;&gt;-->
<!--          </div>-->
        </el-main>
        <el-divider direction="vertical" style="height: 90vh"/>
        <el-aside width="300px" style="height: 90vh;">
          <!--          侧边跳转-->
          <!--          for循环进行题目跳转-->
          <el-card style="width: 280px;margin-top: 40px" v-for="(practice,index) in practices" :key="index">
            <!--            题型-->
            <h3>{{ type[practice.type] }}</h3>
            <el-row :gutter="12">
              <el-col :span="6" v-for="(item,index) in practice.content" :key="item">
                <el-card style="width: 100%;margin-bottom: 10px" shadow="hover" @click="handleGetQuestion(item)">
                  {{ index + 1 }}
                </el-card>
              </el-col>
            </el-row>
          </el-card>
        </el-aside>
        <video id="video" muted="muted" style="float:right;position: fixed;top: 80%;left: 85%" width="200px"
               height="200px" autoplay="autoplay"></video>
        <canvas id="canvas" hidden width="200px" height="200px"></canvas>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped lang="less">
.button-div {
  position: absolute;
  left: 50%;
}

</style>